package com.platform.modules.app.controller;

import com.platform.common.exception.BusinessException;
import com.platform.modules.utils.TencentUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Slf4j
@Controller
@RequestMapping("/app/upload")
public class AppUploadController {

    @Autowired
    private TencentUtil tencentUtil;

    //用于转到upload.html
    @RequestMapping("/totest")
    public String toUpload(){
        return "uploadFile";
    }

    //用于接收文件
    @RequestMapping("/uploadImages")
    @ResponseBody
    public String upload(MultipartFile photo, HttpServletRequest request) throws IOException {
        //判断用户是否上传了文件
        if(!photo.isEmpty()){

            //文件上传的地址
            //String path = ResourceUtils.getURL("classpath:").getPath()+"static/images";
            String path = request.getServletContext().getRealPath("/static/upload");//上下文路径
            String realPath = path.replace('/', '\\').substring(0,path.length());
            //用于查看路径是否正确
            System.out.println(realPath);
            File file1 = new File(realPath);
            if(!file1.exists()){
                file1.mkdirs();
            }

            //获取文件的名称
            String fileName = photo.getOriginalFilename();

            //限制文件上传的类型
            String contentType = photo.getContentType();
            String[] split = contentType.split("/");
            fileName = new Date().getTime()+"."+split[1];
            if("image/jpeg".equals(contentType) || "image/jpg".equals(contentType) || "image/png".equals(contentType)){
                File file = new File(realPath,fileName);
                //完成文件的上传
                photo.transferTo(file);
                System.out.println("图片上传成功!");
                String path01 = "../upload/"+fileName;
                return fileName;
            } else {
                return "fail";
            }
        } else {
            return "fail";
        }
    }

    @PostMapping("/uploadImage")
    @ResponseBody
    public List<String> uploadImage(@RequestParam("file") MultipartFile [] file){
        System.out.println(file[0].getContentType().substring(6));// image/png
        if (file.length < 0) {
            throw new BusinessException("上传出错了:77");
        }
        COSClient cosClient = tencentUtil.tencentStart();
        // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        String bucketName = tencentUtil.getBucketName();
        // 指定要上传到 COS 上对象键
        // 对象键（Key）是对象在存储桶中的唯一标识。例如，在对象的访问域名 `bucket1-1250000000.cos.ap-beijing.myqcloud.com/mydemo.jpg` 中，对象键为 mydemo.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
        List<String> urls = new ArrayList<>();
        try {
            for(int i=0;i<file.length;i++){
                String [] contentType = file[i].getContentType().split("/");
                String key = tencentUtil.getQianzhui() + "/"+ tencentUtil.getQianzhui()+ "_" + new Date().getTime() + "." + contentType[1];
                File localFile = null;
                //将 MultipartFile 类型 转为 File 类型
                localFile = File.createTempFile("temp",null);
                file[i].transferTo(localFile);

                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
                PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
                Map<String,String> map = new HashMap<>();
                urls.add(tencentUtil.getPath()+key);
            }
        }catch (IOException e){
            throw new BusinessException("上传出错了:91");
        }

        return urls;
    }
}
